import { getPropByPath } from 'element-ui/src/utils/util';
import utils from 'axios/lib/utils'

export function objectProperty(obj, pathString, defaultValue) {
    if (typeof pathString !== 'string') {
        return defaultValue
    }
    const res = getPropByPath(obj || {}, pathString, false).v
    if (res || typeof res === 'number' || typeof res === 'boolean') {
        return res
    }
    return defaultValue
}

export function stopAndPreventDomEvent(e) {
    e = e || {}
    if (e.stopPropagation) {
        e.stopPropagation()
    }
    if (e.preventDefault) {
        e.preventDefault()
    }
}
// {} to queryString
export function paramsSerializer(params) {
    const encode = encodeURIComponent
    if (utils.isURLSearchParams(params)) {
        return params.toString();
    }
    var parts = [];
    utils.forEach(params, function serialize(val, key) {
        if (val === null || typeof val === 'undefined') {
            return;
        }
        if (utils.isArray(val)) {
            key = key + '[]';
        } else {
            val = [val];
        }

        utils.forEach(val, function parseValue(v) {
            if (utils.isDate(v)) {
                v = v.toISOString();
            } else if (utils.isObject(v)) {
                v = JSON.stringify(v);
            }
            parts.push(encode(key) + '=' + encode(v));
        });
    });
    return parts.join('&');
}

// 判断是否是空字符串
export function isEmptyString(v) {
    if (v === null || v === undefined || (typeof v === 'string' && v.trim() === '')) {
        return true
    }
    return false
}

// 判断是否是空数组
export function isEmptyArray(v) {
    if (isArray(v) && v.length === 0) {
        return true
    }
    return false
}

export function isObject(v) {
    return Object.prototype.toString.call(v).toLowerCase() === '[object object]';
}

export function isArray(v) {
    return Object.prototype.toString.call(v).toLowerCase() === '[object array]';
}

/**
 * 获取内容宽度
 */
export function getSingleTextWidth(text, fontSize) {
    let calcEl = document.getElementById('maro-pro-text-width-clamp')
    if (!calcEl) {
        calcEl = document.createElement('div')
        calcEl.id = 'maro-pro-text-width-clamp';
        document.body.appendChild(calcEl)
        calcEl.style['width'] = '0px';
        calcEl.style['position'] = 'fixed';
        calcEl.style['top'] = '-100px';
        calcEl.style['height'] = '0px';
        calcEl.style['overflow'] = 'hidden';
        calcEl.style['z-index'] = -1;
        calcEl.style['padding'] = '0px';
        calcEl.style['padding'] = '0px';
        calcEl.style['white-space'] = 'nowrap';
    }
    calcEl.innerHTML = '';  //清空
    calcEl.appendChild(document.createTextNode(String(text)))
    calcEl.style['font-size'] = fontSize
    return getContentElementWidth(calcEl)
}

/**
 * 获取子节点宽度
 * @param {*} parentEl 
 */
export function getContentElementWidth(contentEl) {
    var range = document.createRange()
    range.setStart(contentEl, 0);
    range.setEnd(contentEl, contentEl.childNodes.length);
    return range.getBoundingClientRect().width;
}

/**
 * 获取元素的实际内容宽度
 * @param {*} parentEl 
 */
export function getElementWidth(parentEl) {
    const rectWidth = parentEl.getBoundingClientRect().width
    const padding = (parseInt(window.getComputedStyle(parentEl)['padding-left'], 10) || 0) + (parseInt(window.getComputedStyle(parentEl)['padding-right'], 10) || 0)
    return rectWidth - padding
}
/**
 *  数字转中文
 * @param {*} n 
 * @returns 
 */
export function toChinaNumber(n) {
    // 转字符串
    const number = n + ''
    if (number.match(/\D/) || number.length >= 14) return;
    let zhArray = ['零', '一', '二', '三', '四', '五', '六', '七', '八', '九', '十'];
    let baseArray = ['', '十', '百', '千', '万', '十', '百', '千', '亿', '十', '百', '千', '万'];
    let string = String(number).split('').reverse().map((item, index) => {
        item = Number(item) == 0 ? zhArray[Number(item)] : zhArray[Number(item)] + baseArray[index];
        return item;
    }).reverse().join('');
    string = string.replace(/^一十/, '十');
    string = string.replace(/零+/, '零');
    return string;
}
/**
 * 获取图片实际尺寸大小,参考 https://github.com/fengyuanchen/viewerjs/blob/main/src/js/utilities.js
 * 
 */
export function getImageNaturalSizes(image) {
    const newImage = document.createElement('img');
    let _resolve
    const res = new Promise((resolve) => {
        _resolve = resolve
    })

    if (image.naturalWidth) {
        _resolve({
            width: image.naturalWidth,
            height: image.naturalHeight
        })
        return
    }

    const body = document.body || document.documentElement;
    newImage.onload = () => {
        _resolve({
            width: newImage.width,
            height: newImage.height
        })
        body.removeChild(newImage);
    };
    newImage.src = image.src;
    newImage.style.cssText = (
        'left:0;'
        + 'max-height:none!important;'
        + 'max-width:none!important;'
        + 'min-height:0!important;'
        + 'min-width:0!important;'
        + 'opacity:0;'
        + 'position:absolute;'
        + 'top:0;'
        + 'z-index:-1;'
    );
    body.appendChild(newImage);

    return res;
}
